import React, { useState, useEffect, useRef } from "react";
import { zzy_getType } from "../request/api";
import styles from '../view/App.module.css';

const IndexMain = () => {
  const [list, setList] = useState([]);
  const [page, setPage] = useState(1); // 当前页数
  const [hasMore, setHasMore] = useState(true); // 是否有更多数据
  const loader = useRef(null);

  useEffect(() => {
    loadMoreData(page);
  }, [page]);

  const loadMoreData = (page) => {
    zzy_getType({ page }).then(res => {
      if (res.data.data.length > 0) {
        setList(prevList => [...prevList, ...res.data.data]);
      } else {
        setHasMore(false); // 没有更多数据
      }
    });
  };

  useEffect(() => {
    const observer = new IntersectionObserver(
      entries => {
        if (entries[0].isIntersecting && hasMore) {
          setPage(prevPage => prevPage = 1);
        }
      },
      { threshold: 1.0 }
    );

    if (loader.current) {
      observer.observe(loader.current);
    }

    return () => {
      if (loader.current) {
        observer.unobserve(loader.current);
      }
    };
  }, [hasMore]);

  return (
    <>
      <div className={styles.menumax}>
        {list.map((item, index) => (
          <div key={item._id} className={styles.menubox}>
            <h3>{item.typeName}</h3>
            <img src={item.imgSrc} alt="" className={styles.menuimg} />
          </div>
        ))}
      </div>
      {hasMore && <h2 ref={loader} className={styles.loader}>加载更多.......</h2>}
    </>
  );
};

export default IndexMain;